<template>
  <centre>
    <el-form ref="ruleForm" :model="form" :rules="rules" label-width="60px" class="form">
      <h3>用户登录</h3>
      <el-form-item label="用户" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('ruleForm')" @keyup.prevent="onSubmit('ruleForm')">登录</el-button>
        <el-button @click="onReset('ruleForm')">取消</el-button>
      </el-form-item>
    </el-form>
  </centre>
</template>

<script>
import Centre from "@/components/Centre";
// import * as userServices from '../services/userServices'

export default {
  name: "Login",
  components: {
    Centre
  },
  data() {
    return {
      form: {
        username: '',
        password: '',
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: blur},
          {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: blur}
        ]
      }
    }
  },
  methods: {
    onSubmit(form) {
      this.$refs[form].validate((valid) => {
        // 验证通过
        if (valid) {
          this.$store.dispatch('loginUser/login',this.form).then((res)=>{
            if (res === 1){
              this.$message.success('登录成功')
              // 登录成功，跳转到 首页
              this.$router.push({name: 'home'});
            }else {
              this.$message.error('登录失败')
            }
          })
        } else {
          return false;
        }
      })
    },
    onReset(form) {
      this.$refs[form].resetFields();
    }
  }
}
</script>

<style scoped lang="scss">
.form {
  width: 340px;
  padding: 32px 48px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);

  h3 {
    font-size: 1.7rem;
    text-align: center;
    margin-bottom: 32px;
    color: #303133;
  }
}
</style>
